package com.rpc.provider;

import com.rpc.center.register.client.CenterRegisterFactory;
import com.rpc.center.register.client.RPCRegisterService;
import com.rpc.common.entity.request.PublishDTO;
import com.rpc.provider.configer.PublishConfiger;
import com.rpc.common.exception.RPCProcessException;
import com.rpc.provider.handler.RPCProcessServer;
import com.rpc.provider.manager.RPCInvokeTargetManager;
import com.sun.istack.internal.NotNull;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class RPCProvider {
    private String serverInterface; //服务接口全限定类名
    private String version; //版本号
    private String group;   //服务分组
    private Object target;
    private RPCRegisterService register;
    //发布服务
    public void publish(@NotNull PublishConfiger configuer) {

        PublishDTO publishDTO = new PublishDTO();
        publishDTO.setGroup(group);
        //设置本地提供服务的端口号和地址
        publishDTO.setPort(configuer.getPort());
        if(configuer.getHostAddress().isEmpty()){
            throw new RuntimeException("没有提供服务地址");
        }
        publishDTO.setHostAddress(configuer.getHostAddress());
        if(version.isEmpty()){
            //没有设置版本号，则使用默认地址
            publishDTO.setVersion("1.0.0");
        }else{
            publishDTO.setVersion(version);
        }
        if(serverInterface.isEmpty()){
            throw new RuntimeException("服务名不能为空");
        }else{
            try {
                Class servive=Class.forName(serverInterface);
                if(!servive.isInterface()){
                    throw new RuntimeException("服务名并非一个接口名");
                }
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("服务名错误，找不到对应类型");
            }
        }
        publishDTO.setInterfaceName(serverInterface);
        //服务注册
        register = CenterRegisterFactory.getRegisterInstance(configuer.getServerAddress(),configuer.getServerPort());   //通过注册工厂获得注册器
        register.publish(publishDTO);
        //添加服务名和调用对象的映射到RPC调用对象管理器中
        RPCInvokeTargetManager.addInvokeTarget(serverInterface, target);

        //开启服务发布方网络服务
        RPCProcessServer server = RPCProcessServer.getRPCProcessServerInstance();
        server.setConfiger(configuer);
        try {
            server.startServer();
        } catch (RPCProcessException e) {
            System.out.println("服务启动失败");
            e.printStackTrace();
        }
    }

    /**
     * 重载设置服务接口名，接受一个Class类型而不是字符串，所以可以更加安全
     * @param service
     */
    public void setServiceInterface(Class service){
        if(service.isInterface()){
            this.serverInterface=service.getCanonicalName();
        }
    }

    /**
     * 设置服务接口名
     * @param serverInterface
     */
    public void setServerInterface(String serverInterface) {
        this.serverInterface = serverInterface;
    }
}
